package com.moyun.modelclass.dialog;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.graphics.Color;
import android.view.Display;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;

import androidx.lifecycle.LifecycleOwner;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.blankj.utilcode.util.ClickUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.hjq.http.EasyHttp;
import com.hjq.http.listener.HttpCallback;
import com.hjq.http.listener.OnHttpListener;
import com.moyun.modelclass.adapter.ConfigPrintParamsAdapter;
import com.moyun.modelclass.adapter.ModelAssociationAdapter;
import com.moyun.modelclass.http.CommonConfiguration;
import com.moyun.modelclass.http.api.AppModelListApi;
import com.moyun.modelclass.http.api.ConfigPrintParamsApi;
import com.moyun.modelclass.http.api.ModelListApi;
import com.moyun.modelclass.http.api.ModelRelateModelListApi;
import com.moyun.modelclass.http.api.ShoppingCartListApi;
import com.moyun.modelclass.http.bean.ModelResponse;
import com.moyun.modelclass.http.bean.OrderRequestResponse;
import com.moyun.modelclass.http.model.HttpData;
import com.moyun.modelclass.R;
import com.moyun.modelclass.view.recyclerview.DividerItemDecoration;

import java.util.ArrayList;
import java.util.List;

/**
 * 作者：Meteor
 * tip：关联模型弹窗
 */
public class AssociationModelDialog implements ModelAssociationAdapter.OnCheckedClick {
    private ImageView dialogAssociationModelClose;
    private RadioGroup rgAssociationModelType;
    private RadioButton rbAssociationModelAll;
    private RadioButton rbAssociationModelUploaded;
    private RadioButton rbAssociationModelPurchased;
    private RecyclerView dialogAssociationModelRecycler;
    private TextView tvAssociationModelSave;

    @SuppressLint("StaticFieldLeak")
    private static AssociationModelDialog alertDialog = null;
    private final Activity context;
    private Dialog dialog;
    private final Display display;
    private ModelAssociationAdapter modelAssociationAdapter = new ModelAssociationAdapter();
    private OnModelListListener onModelListListener;
    private List<ModelResponse> mModelCheckList = new ArrayList<>();

    public static AssociationModelDialog getInstance(Activity context, OnModelListListener onModelListListener) {
        if (alertDialog == null) {
            synchronized (AlertDialog.class) {
                if (alertDialog == null) {
                    alertDialog = new AssociationModelDialog(context, onModelListListener);
                }
            }
        }
        return alertDialog;
    }

    public AssociationModelDialog(Activity context, OnModelListListener onModelListListener) {
        this.context = context;
        this.onModelListListener = onModelListListener;
        WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
        display = windowManager.getDefaultDisplay();
    }

    public AssociationModelDialog builder() {
        View view = LayoutInflater.from(context).inflate(R.layout.dialog_association_model, null);
        dialogAssociationModelClose = (ImageView) view.findViewById(R.id.dialog_association_model_close);
        rgAssociationModelType = (RadioGroup) view.findViewById(R.id.rg_association_model_type);
        rbAssociationModelAll = (RadioButton) view.findViewById(R.id.rb_association_model_all);
        rbAssociationModelUploaded = (RadioButton) view.findViewById(R.id.rb_association_model_uploaded);
        rbAssociationModelPurchased = (RadioButton) view.findViewById(R.id.rb_association_model_purchased);
        dialogAssociationModelRecycler = (RecyclerView) view.findViewById(R.id.dialog_association_model_recycler);
        tvAssociationModelSave = (TextView) view.findViewById(R.id.tv_association_model_save);


        dialogAssociationModelRecycler.setLayoutManager(new LinearLayoutManager(context));
        dialogAssociationModelRecycler.addItemDecoration(new DividerItemDecoration(
                context,
                Color.parseColor("#EEEEEE"),
                1,
                SizeUtils.dp2px(17),
                SizeUtils.dp2px(17)));
        dialogAssociationModelRecycler.setAdapter(modelAssociationAdapter);
        modelAssociationAdapter.setOnCheckedClick(this);
        modelListData(true, 1);

        // 定义Dialog布局和参数
        dialog = new Dialog(context, R.style.common_dialog);
        dialog.setContentView(view);
        dialog.getWindow().setGravity(Gravity.BOTTOM);
        dialog.setCanceledOnTouchOutside(false);//点击屏幕 dialog不消失
        dialog.setCancelable(false);//点击屏幕或返回按钮 dialog不消失
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);
        WindowManager.LayoutParams attributes = dialog.getWindow().getAttributes();
        attributes.width = (int) (display.getWidth());
        dialog.getWindow().setAttributes(attributes);

        ClickUtils.applySingleDebouncing(dialogAssociationModelClose, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (onModelListListener != null) {
                    alertDialog = null;
                    dialog.dismiss();
                    onModelListListener.cancel();
                }
            }
        });

        rgAssociationModelType.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if (checkedId == R.id.rb_association_model_all) {
                    //全部
                    rbAssociationModelAll.setSelected(true);
                    rbAssociationModelUploaded.setSelected(false);
                    rbAssociationModelPurchased.setSelected(false);
                    modelAssociationAdapter.setSelectedItems();
                    modelListData(true, 1);
                } else if (checkedId == R.id.rb_association_model_uploaded) {
                    //已上传
                    rbAssociationModelAll.setSelected(false);
                    rbAssociationModelUploaded.setSelected(true);
                    rbAssociationModelPurchased.setSelected(false);
                    modelAssociationAdapter.setSelectedItems();
                    modelListData(true, 2);
                } else if (checkedId == R.id.rb_association_model_purchased) {
                    //已购买
                    rbAssociationModelAll.setSelected(false);
                    rbAssociationModelUploaded.setSelected(false);
                    rbAssociationModelPurchased.setSelected(true);
                    modelAssociationAdapter.setSelectedItems();
                    modelListData(true, 3);
                }
            }
        });

        ClickUtils.applySingleDebouncing(tvAssociationModelSave, new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mModelCheckList == null || mModelCheckList.size() <= 0) {
                    ToastUtils.showShort("选择模型");
                    return;
                }
                if (onModelListListener != null) {
                    alertDialog = null;
                    dialog.dismiss();
                    onModelListListener.content(mModelCheckList);
                }
            }
        });
        return this;
    }

    private void modelListData(boolean isRefresh, int relateType) {
        EasyHttp.post((LifecycleOwner) context)
                .api(new ModelRelateModelListApi().setIndex(-1).setModelRelateType(relateType).setPageSize(CommonConfiguration.page * 2))
                .request(new HttpCallback<HttpData<ModelRelateModelListApi.Bean>>((OnHttpListener) context) {
                    @Override
                    public void onSucceed(HttpData<ModelRelateModelListApi.Bean> result) {
                        if (result != null && result.getData() != null && result.getData().getList().size() > 0) {
                            List<String> ids = new ArrayList<>();
                            for (ModelRelateModelListApi.BeanInfo beanInfo : result.getData().getList()) {
                                if (beanInfo != null) {
                                    ids.add(beanInfo.getModelId());
                                }
                            }
                            initModelListLog(isRefresh, ids);
                        }else {
                            if (isRefresh) {
                                modelAssociationAdapter.setList(new ArrayList<>());
                                modelAssociationAdapter.setEmptyView(R.layout.empty_view_layout);
                            }
                        }
                    }
                });
    }

    //通过模型id列表批量获取模型数据
    private void initModelListLog(boolean isRefresh, List<String> modelIdList) {
        if (modelIdList.size() <= 0) {
            ToastUtils.showShort("模型id列表为空");
            return;
        }
        EasyHttp.post((LifecycleOwner) context)
                .api(new AppModelListApi().setModelIdList(modelIdList).setScene(1))
                .request(new HttpCallback<HttpData<AppModelListApi.Bean>>((OnHttpListener) context) {
                    @Override
                    public void onSucceed(HttpData<AppModelListApi.Bean> result) {
                        if (result != null && result.getData() != null && result.getData().getList().size() > 0) {
                            if (isRefresh) {
                                modelAssociationAdapter.setList(result.getData().getList());
                            } else {
                                modelAssociationAdapter.addData(result.getData().getList());
                            }
                        } else {
                            if (isRefresh) {
                                modelAssociationAdapter.setList(new ArrayList<>());
                                modelAssociationAdapter.setEmptyView(R.layout.empty_view_layout);
                            }
                        }
                    }
                });
    }

    public void show() {
        if (!context.isFinishing()) {
            dialog.show();
        }
    }

    @Override
    public void Checked(List<ModelResponse> ModelList) {
        mModelCheckList.clear();
        mModelCheckList = ModelList;
    }

    public interface OnModelListListener {
        void content(List<ModelResponse> modelResponseList);

        void cancel();
    }
}
